#pragma once
#include <iostream>
#include <pthread.h>

#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Log.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"


 
#define PORT 8888


class HttpServer
{
private:
    int16_t _port;
    bool _stop;
public:
    HttpServer(uint16_t port = PORT)
        :_port(port), _stop(false)
    {}

    void Init()
    {
        signal(SIGPIPE, SIG_IGN);   //防止通信时对端关闭，导致服务挂掉
        //_tcpSvr = TcpServer::GetInstance(_port);
    }

    void Loop()
    {
        LOG(NORMAL, "HttpServer loop...");
        //int listenSock =_tcpSvr->Sockfd();
        TcpServer* tcpSvr = TcpServer::GetInstance(_port);
        while(!_stop)
        {
            struct sockaddr_in peer;        //  接收对方套接字
            socklen_t len = sizeof(peer);   //  输入peer长度 输出实际获取长度

            int sock = accept(tcpSvr->Sockfd(), (struct sockaddr*)&peer, &len);
            if(sock < 0)
            {
                LOG(FATAL, "accept fail");
                continue;
            }

            //链接创立成功， 创建线程去处理链接
            LOG(NORMAL, "Get a new link...");
            
            Task task(sock);
            ThreadPool::GetInstance()->PushTask(task);

        }
    }


    ~HttpServer()
    {}
};